package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.common.RabbitService;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public String createAliPay(Long orderId) throws AlipayApiException {
        //  根据订单Id 获取到订单对象
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        //  保存交易记录.
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        //  验证：订单是否已过期或支付
        if ("CLOSED".equals(orderInfo.getOrderStatus()) || "PAID".equals(orderInfo.getOrderStatus())){
            return "该订单已支付或已关闭";
        }
        //  AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipay.com/gateway.do" , APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);  //获得初始化的AlipayClient
        //  支付请求对象
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        //	设置同步回调地址.
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //	设置异步回到地址.
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url); //在公共参数中设置回跳和通知地址
        //  业务参数： 只有一个商家收款.
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("total_amount", 0.01);
        bizContent.put("subject", orderInfo.getTradeBody());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //  二维码失效时间.
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,10);
        bizContent.put("time_expire", simpleDateFormat.format(calendar.getTime()));
        alipayRequest.setBizContent(bizContent.toString());
        return alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单

    }

    @Override
    public Boolean refund(Long orderId) {
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //  发起的退款请求对象.
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        //  bizContent.put("trade_no", "2021081722001419121412730660");
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
        bizContent.put("out_request_no", "HZ01RF001");

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            //  退款成功.  修改交易记录状态. 订单状态.
            if ("Y".equals(response.getFundChange())){
                PaymentInfo paymentInfo = new PaymentInfo();
                paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                //  调用更新方法.
                this.paymentService.updatePaymentStatus(paymentInfo,orderInfo.getOutTradeNo(),PaymentType.ALIPAY.name());
                //  发送消息:
                this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_ORDER_CLOSED,MqConst.ROUTING_ORDER_CLOSED,orderInfo.getId());
                return true;
            } else {
              return false;
            }
            //  System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean closePay(Long orderId) {
        //  根据订单Id 获取到订单 对象.
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        //  创建支付宝关闭对象.
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        //  构建查询参数.
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean checkPayment(Long orderId) {
        //  根据订单Id 获取到订单 对象.
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //  创建查询对象
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            if ("WAIT_BUYER_PAY".equals(response.getTradeStatus())){
                System.out.println("等待付款.");
            }else if ("TRADE_CLOSED".equals(response.getTradeStatus())){
                System.out.println("交易关闭.");
            }else {
                System.out.println("支付成功.");
            }
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }
}
